package com.ikunikun.aspect;

import com.ikunikun.annotation.AutoFill;
import com.ikunikun.constant.AutoFillConstant;
import com.ikunikun.context.BaseContext;
import com.ikunikun.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 自定义切面类，实现公共字段自动填充
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
	//切入点
	@Pointcut("execution(* com.ikunikun.mapper.*.*(..)) && @annotation(com.ikunikun.annotation.AutoFill)")
	public void autoFillPointCut(){}

	// 定义前置通知，在通知中为公共字段赋值
	@Before("autoFillPointCut()")
	public void autoFill(JoinPoint joinPoint){
		// 获取当前被拦截的方法上的数据库操作类型
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 方法签名对象
		AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);// 获得方法注解对象
		OperationType operationType = annotation.value();// 获得数据库操作类型

		// 准备数据
		Long id = BaseContext.getCurrentId();
		LocalDateTime now = LocalDateTime.now();

		// 获得当前被拦截方法的参数--实体对象
		Object[] args = joinPoint.getArgs();
		if (Objects.isNull(args)){
			return;
		}
		Object entity = args[0];

		// 根据不同的操作类型，为对应的属性通过反射来赋值
		try {
			Method updateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
			Method updateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
			updateTime.invoke(entity,now);
			updateUser.invoke(entity,id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (operationType == OperationType.INSERT){
			try {
				Method createTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
				Method createUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
				createTime.invoke(entity,now);
				createUser.invoke(entity,id);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.info("公共字段自动填充中...");
	}
}
